package com.cloud.common.core.configure;

import com.cloud.common.core.constant.GateWayConstant;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.Base64Utils;

/**
 * @Description: Feign请求拦截器 主要目的是使用Feign调用其他服务接口时，拦截到请求，并把请求头里的信息往下传递
 * @Auther: zhangxun
 * @Date: 2020/8/13 17:53
 */

public class OAuth2FeignConfigure {
    // 过SecurityContextHolder从请求上下文中获取了OAuth2AuthenticationDetails类型对象，并
    // 通过该对象获取到了请求令牌，然后在请求模板对象requestTemplate的头部手动将令牌添加上去
    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        return requestTemplate -> {
            // 添加 Gateway Token
            String gatewayToken = new String(Base64Utils.encode(GateWayConstant.GATEWAY_TOKEN_VALUE.getBytes()));
            requestTemplate.header(GateWayConstant.GATEWAY_TOKEN_HEADER, gatewayToken);

            Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();
            if (details instanceof OAuth2AuthenticationDetails) {
                String authorizationToken = ((OAuth2AuthenticationDetails) details).getTokenValue();
                requestTemplate.header(HttpHeaders.AUTHORIZATION, "bearer " + authorizationToken);
            }
        };
    }
}